﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using GMS.Client.Core;
using GMS.Client.Model;
using GMS.Client.Resources;
using GMS.Client.Utility;

namespace GMS.Client.Domain
{
    /// <summary>
    /// 游戏领域类
    /// </summary>
    public class GameService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="user"></param>
        public GameService(GameInfo gameInfo)
        {
            Console.WriteLine("{0}启动游戏服务{1}...", DateTime.Now, gameInfo.TitleName);
            this.gameInfo = gameInfo;
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        private GameInfo gameInfo { get; set; }

        private string D3Name = "Diablo III";

        /// <summary>
        /// 语种
        /// </summary>
        private Language language = new CN();

        /// <summary>
        /// 是否已初始化
        /// </summary>
        /// <returns></returns>
        public bool IsRun { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        public Window Init(Window tnt)
        {
            Console.WriteLine("{0}初始化{1}...", DateTime.Now, gameInfo.TitleName);

            Win32API.MoveWindow(tnt.Handle, gameInfo.TNTPosition.X, gameInfo.TNTPosition.Y);

            tnt.Controls = new List<CustomControl>();

            var tabControl = new TabControl(Win32API.GetParent(Win32API.GetChildWindowHandle(tnt.Handle, null, language.MainWindow, 10)));
            tabControl.InitTabPages();

            var attackMosterInfoPanelHandle = Win32API.GetChildWindowHandle(tnt.Handle, null, language.AttackMosterInfo, 10);
            var attackMosterInfoPanelChildHandles = Win32API.GetChildHandlesByParentHandle(attackMosterInfoPanelHandle);

            tnt.Controls.Add(new TextBox(attackMosterInfoPanelChildHandles[10], CustomControlNameType.Txt_Exp));
            tnt.Controls.Add(new TextBox(attackMosterInfoPanelChildHandles[1], CustomControlNameType.Txt_DeathTimes));
            tnt.Controls.Add(new TextBox(attackMosterInfoPanelChildHandles[12], CustomControlNameType.Txt_LootGold));

            var tntCardInfoPanelHandle = Win32API.GetChildWindowHandle(tnt.Handle, null, language.TNTCardInfo, 10);
            var tntCardInfoPanelChildHandles = Win32API.GetChildHandlesByParentHandle(tntCardInfoPanelHandle);
            tnt.Controls.Add(new Label(tntCardInfoPanelChildHandles[6], CustomControlNameType.Lbl_IsLoginSuccess));

            var loginHandle = Win32API.GetChildWindowHandle(tnt.Handle, null, language.Btn_Login, 10);
            var intiD3Handle = Win32API.GetChildWindowHandle(tnt.Handle, null, language.Btn_InitD3, 10);

            tnt.Controls.Add(new Button(loginHandle, CustomControlNameType.Btn_Login));
            tnt.Controls.Add(new Button(intiD3Handle, CustomControlNameType.Btn_InitD3));

            var coreScriptPanelHandle = Win32API.GetChildWindowHandle(tnt.Handle, null, language.CoreScript, 10);
            var coreScriptPanelChildHandles = Win32API.GetChildHandlesByParentHandle(coreScriptPanelHandle);
            tnt.Controls.Add(new TextBox(coreScriptPanelChildHandles[0], CustomControlNameType.Txt_CoreScript));
            return tnt;
        }

        /// <summary>
        /// 运行
        /// </summary>
        public void Run(Window tnt)
        {
            Console.WriteLine("{0}运行{1}...", DateTime.Now, gameInfo.TitleName);
            var btn_Start = GetControl<Button>(tnt, CustomControlNameType.Btn_Start);
            btn_Start.Click();

            Win32API.SetForegroundWindow(Win32API.FindWindow(null, language.GameWindowTitle));

            IsRun = true;
        }

        /// <summary>
        /// 退出
        /// </summary>
        public void Exit()
        {
            Clear();
        }

        /// <summary>
        /// 登录
        /// </summary>
        public Window Login(Window tnt)
        {
            Console.WriteLine("{0}登录{1}...", DateTime.Now, gameInfo.TitleName);
            var btnLogin = GetControl<Button>(tnt, CustomControlNameType.Btn_Login);
            var btnInitD3 = GetControl<Button>(tnt, CustomControlNameType.Btn_InitD3);
            var lblIsLoginSuccess = GetControl<Label>(tnt, CustomControlNameType.Lbl_IsLoginSuccess);
            var txtCoreScript = GetControl<TextBox>(tnt, CustomControlNameType.Txt_CoreScript);

            btnLogin.Click();

            var loginResult = string.Empty;

            while (string.IsNullOrWhiteSpace(loginResult))
            {
                loginResult = lblIsLoginSuccess.GetValue();
                Thread.Sleep(500);
            }

            if (loginResult.Equals(language.LoginSuccess, StringComparison.CurrentCultureIgnoreCase))
            {
                btnInitD3.Click();

                var txtCoreScriptValue = string.Empty;
                while (string.IsNullOrWhiteSpace(txtCoreScriptValue))
                {
                    txtCoreScriptValue = txtCoreScript.GetValue<string>();
                    Thread.Sleep(500);
                }
                Win32API.MoveWindow(ProcessHelper.Find(D3Name, gameInfo.D3FullPath), gameInfo.D3Position.X, gameInfo.D3Position.Y);

                var mainHandles = Win32API.GetChildHandlesByParentHandle(tnt.Handle);
                var btn_Start = new Button(mainHandles[1], CustomControlNameType.Btn_Start);
                tnt.Controls.Add(btn_Start);
            }
            return tnt;
        }

        /// <summary>
        /// 获取控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="customControlNameType"></param>
        /// <returns></returns>
        private T GetControl<T>(Window tnt, CustomControlNameType customControlNameType) where T : CustomControl
        {
            return (T)tnt.Controls.Single(c => c.CustomControlNameType == customControlNameType);
        }

        /// <summary>
        /// 清理环境
        /// </summary>
        public void Clear()
        {
            Console.WriteLine("{0}清理{1}...", DateTime.Now, gameInfo.TitleName);
            ProcessHelper.Kill(gameInfo.TitleName, gameInfo.FileName);
            ProcessHelper.Kill(D3Name, gameInfo.D3FullPath);
            Thread.Sleep(1000);
        }

        /// <summary>
        /// 设置游戏配置信息
        /// </summary>
        public void SetGameConfig()
        {
            Console.WriteLine("{0}设置游戏配置信息{1}...", DateTime.Now, gameInfo.TitleName);
            var xmlHelper = new XmlHelper(gameInfo.WorkingDirectory + @"\config.xml");
            xmlHelper.SetValue(gameInfo.Config.Name, gameInfo.Config.Value);
            xmlHelper.Save();
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <returns></returns>
        public Window Start()
        {
            Console.WriteLine("{0}启动{1}...", DateTime.Now, gameInfo.TitleName);
            ProcessHelper.Start(gameInfo.FileName, gameInfo.WorkingDirectory);
            var tnt = new Window(null, gameInfo.TitleName);
            var i = 0;
            while (tnt.Handle == IntPtr.Zero)
            {
                tnt = new Window(null, gameInfo.TitleName);
                Thread.Sleep(1000);
                i++;
                if (i > 100)
                {
                    throw new Exception("超过最大尝试数，TNT窗口捕获失败");
                }
            }
            return Init(tnt);
        }

        public bool FindWindow(IntPtr handle)
        {
            var tnt = new Window(null, gameInfo.TitleName);
            return tnt.Handle == handle;
        }
    }
}
